<?php
/**
 *  💡 免责声明：本软件不得用于商业用途，仅做学习交流
 *  ⚠️ 权利声明：本软件由版权人提供产品技术支持
 *  📅 项目编号：NX2025-0135
 */
namespace App\Service\User;

use App\Jobs\UpdateUserRevenueJob;
use App\Models\GoldBeanAccount;
use App\Models\GroupOrder;
use App\Models\PerformanceMember;
use App\Models\PointAccount;
use App\Models\PointTransaction;
use App\Models\ProductOrder;
use App\Models\User;
use App\Models\UserRewardAccount;
use App\Models\UserTotalRevenue;
use App\Models\WalletAccount;
use App\Service\AdvanceCard\AdvanceCardService;
use App\Service\BaseService;
use App\Service\Notifications\NotificationService;
use App\Service\Setting\UserSettingService;
use Illuminate\Support\Facades\DB;

class UserServices extends BaseService
{
    public function InitUserAccount(User $user)
    {
        DB::transaction(function () use ($user) {
            $this->InitPointAccount($user);
            $this->InitWalletAccount($user);
            $this->InitGoldBeanAccounts($user);
            $this->InitRewardAccounts($user);
            $this->InitUserTotalRevenues($user);
        });
    }

    /**
     * 初始化用户总收益.
     */
    public function InitUserTotalRevenues(User $user)
    {
        UserTotalRevenue::query()->firstOrCreate([
            'user_id' => $user->getKey(),
        ], [
            'value' => 0,
        ]);
    }

    //L1，L2，L3 拼单会员直推 5 个人成功升级为拼单会员也可直接升级到 L4 级别
    public function parentUpLevel(User $user)
    {
        $parent = $user->getParent();
        if (blank($parent)) {
            return;
        }
        if (in_array($parent->member_level, [1, 2, 3])) {
            $count = $parent->queryChildren()->where('member_level', '>', 0)->count();
            if ($count >= 5) {
                $this->designateUserLevel(4, $parent);
                if (filled($user)) {
                    NotificationService::make()->SystemNotify($user, '直推5人成功提升会员等级!系统以为您升级为：LV4');
                }
            }
        }
    }

    /**
     * 金额更新用户等级.
     * @param $amount
     * @param $user_id
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|void
     */
    public function amountUpdateUserLevel($amount, User $user)
    {
        $levelSetting = UserSettingService::make()->matchingLevel($amount);
        if (blank($levelSetting)) {
            return;
        }
        //发放代金券
        AdvanceCardService::make()->apply($user->id, $levelSetting->frequency * 500);

        if ($levelSetting->level != $user->member_level) {
            $this->designateUserLevel($levelSetting->level, $user);
            $this->parentUpLevel($user);
//            if (filled($user)) {
//                NotificationService::make()->SystemNotify($user, "您拼单等级已变更为：LV{$levelSetting->level}");
//            }
        }
        return $levelSetting;
    }

    /**
     * 指定用户等级.
     * @param $level
     * @param $user_id
     */
    public function designateUserLevel($level, User $user)
    {
        $user->member_level = $level;
        $user->save();
    }

    /**
     * 获取父级.
     * @param $distance 深度
     */
    public function getParent(User $user, $distance = 2)
    {
        if ($user->isRoot()) {
            //自己就是根节点没有上级
            return null;
        }
        //获取所以不包含自己的祖先
        $ancestor = $user->queryAncestors()
            ->where('distance', '<=', $distance)
            ->get();
        return $ancestor->groupBy('distance')->map(function ($item) {
            return $item[0];
        });
    }

    /**
     * 获取直接下级.
     * @param $distance 深度
     */
    public function getChildren(User $user, $distance = 2)
    {
        //获取所以不包含自己的祖先
        $ancestor = $user->queryDescendants()
            ->where('distance', '<=', $distance)
            ->get();
        return $ancestor->groupBy('distance');
    }

    public function addPerformance()
    {
    }

    public function reconstructTheBenefits() //重构收益 会大量计算
    {
//        User::query()->update([
//            'agent_level' => 0,   //清楚代理商等级
//        ]);
        UserTotalRevenue::query()->update([
            'value' => 0,
            'self' => 0,
            'product' => 0,
            'group' => 0,
            'group_team' => 0,
            'product_team' => 0,
        ]);
        PerformanceMember::query()->update([
            'total_amount' => 0,
            'max_team_amount' => 0,
            'small_teams_sum' => 0,
            'team_data' => null,
        ]);

        //拼团订单构建收益
        GroupOrder::with('user')->where('status', '>', 2)
            ->chunkById(100, function ($orders) {
                $orders->each(function ($order) {
                    UpdateUserRevenueJob::dispatch($order->user, $order->amount, 2)
                        ->onQueue('update_user_revenue');
                });
            });
        //普通商品构建
        ProductOrder::with('user')->where('status', '>', 2)->chunkById(100, function ($orders) {
            $orders->each(function ($order) {
                UpdateUserRevenueJob::dispatch($order->user, $order->total_amount, 1)
                    ->onQueue('update_user_revenue');
            });
        });
    }

    /**
     * 初始化钱包.
     */
    protected function InitWalletAccount(User $user)
    {
        WalletAccount::query()->firstOrCreate([
            'user_id' => $user->getKey(),
        ], ['user_id' => $user->getKey()]);
    }

    /**
     * 初始化积分账户.
     */
    protected function InitPointAccount(User $user)
    {
        PointAccount::query()->firstOrCreate([
            'user_id' => $user->getKey(),
        ], ['user_id' => $user->getKey(), 'total_point' => 10, 'available_points' => 10, 'withdraw_points' => 10]);
        PointTransaction::query()->create([
            'user_id' => $user->getKey(),
            'amount' => 10,
            'balance' => 10,
            'transaction_type' => 1,
            'status' => 2,
            'describe' => '新用户注册奖励 积分:10',
            'change_type' => 1,
        ]);
    }

    /**
     * 初始化KC通证账户.
     */
    protected function InitGoldBeanAccounts(User $user)
    {
        GoldBeanAccount::query()->firstOrCreate([
            'user_id' => $user->getKey(),
        ], ['user_id' => $user->getKey()]);
    }

    /**
     * 初始化奖励余额.
     */
    protected function InitRewardAccounts(User $user)
    {
        UserRewardAccount::query()->firstOrCreate([
            'user_id' => $user->getKey(),
        ], ['user_id' => $user->getKey()]);
    }
}
